<template>
  <div class="spatialDialogContainer" v-if="isSpatialDialogShow" v-drag>
    <div class="spatialDialogTitle drag-handle">
      <div class="title-left">
        <div class="bar"></div>
        <div class="title-text">空间查询统计</div>
      </div>
      <div class="title-right">
        <div tabindex="0" class="icon" @click="closeDialog">×</div>
      </div>
    </div>
    <div class="spatialDialogContent">
      <div class="contentButton">
        <div
          class="menuButton"
          :class="{ active: isNormalShow }"
          @click="changeMenu('normal')"
        >
          区域查询
        </div>
        <div
          class="menuButton"
          :class="{ active: isAdvancedShow }"
          @click="changeMenu('advanced')"
        >
          区域设置
        </div>
      </div>
      <div
        v-if="isNormalShow"
        style="
          width: 100%;
          height: 30px;
          background-color: rgb(64, 112, 162);
          font-size: 16px;
          color: white;
          line-height: 30px;
        "
      >
        统计条件设定
      </div>
      <div v-if="isNormalShow" style="display: flex; justify-content: center">
        <div class="conditionContent" style="width: 100%; max-height: 10rem">
          <div
            class="conditionContent-type"
            style="
              display: flex;
              margin: 0 auto;
              justify-content: center;
              margin-top: 5px;
            "
          >
            <div style="display: flex; width: 100%">
              <div
                style="
                  width: 105px;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isAllAreaShow }"
                @click="changeArea('all')"
              >
                全部区域
              </div>
              <div
                style="
                  width: 105px;
                  height: 25px;
                  margin-left: -3px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isNowAreaShow }"
                @click="changeArea('now')"
              >
                当前区域
              </div>
              <div
                style="
                  width: 120px;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isEnvShow }"
                @click="changeArea('env')"
              >
                自定义矩形
              </div>
              <div
                style="
                  width: 120px;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isCoorShow }"
                @click="changeArea('coor')"
              >
                自定义多边形
              </div>
            </div>
          </div>
          <div
            class="conditionContent-area"
            style="width: 300px; display: flex; margin-top: 10px"
          >
            <div
              v-show="isNowAreaShow"
              class="label"
              style="width: 60px; font-weight: bold"
            >
              区域
            </div>
            <div v-show="isNowAreaShow">
              <select
                v-model="targetOption"
                @change="targetSelect"
                style="width: 240px"
              >
                <option
                  v-for="item in templateTableData"
                  :key="item.areaValue"
                  :value="item.areaValue"
                >
                  {{ item.areaName }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <div v-if="isNormalShow">
        <div
          style="
            width: 96%;
            height: 30px;
            background-color: rgb(64, 112, 162);
            font-size: 16px;
            color: white;
            line-height: 30px;
            display: flex;
            align-items: center;
            padding: 0px 10px;
            margin-bottom: 0.25rem;
          "
        >
          <span>统计类型：</span>
          <select
            v-model="selectedMainType"
            @change="handleMainSelectChange"
            style="
              width: 100px;
              height: 100%;
              color: black;
              background-color: #f0f0f0;
              border: 1px solid #ccc;
              padding: 0 5px;
              font-size: 16px;
            "
          >
            <option value="管网节点">设备数据</option>
            <option value="管网线段">管线数据</option>
          </select>
          <select
            v-model="selectedDetailType"
            @change="handleDetailSelectChange"
            style="
              width: 150px;
              height: 100%;
              color: black;
              background-color: #f0f0f0;
              border: 1px solid #ccc;
              padding: 0 5px;
              font-size: 16px;
              margin-left: 1rem;
            "
            v-if="
              selectedMainType &&
              Object.keys(spatialQueryData[selectedMainType] || {}).length > 0
            "
          >
            <option
              v-for="(item, index) in getDetailOptions(selectedMainType)"
              :key="index"
              :value="item"
            >
              {{ item }}
            </option>
          </select>
        </div>
        <div
          v-if="isNormalShow"
          style="
            display: flex;
            width: 100%;
            height: 30px;
            background-color: #4070a2;
            font-size: 16px;
            color: white;
            line-height: 30px;
            margin-top: 1rem;
            align-items: center;
          "
        >
          <div style="flex: 1; text-align: left; padding-left: 10px">
            统计结果
          </div>
          <div
            v-if="isTotalShow"
            style="flex: 1; text-align: right; padding-right: 10px"
          >
            <div v-if="isPipeLineShow">总长：{{ total }} 公里</div>
            <div v-else>总数量 {{ total }} 个</div>
          </div>
        </div>

        <div
          v-loading="isLoading"
          element-loading-text="正在加载数据中..."
          v-if="isNormalShow"
        >
          <el-table
            :data="tableData"
            border
            id="dataTable"
            height="250"
            style="width: 100%"
            @row-click="handlePointListClick"
          >
            <el-table-column prop="cnname" label="关键字"></el-table-column>
            <el-table-column prop="material" label="材质"></el-table-column>
            <el-table-column prop="equipmentNum" label="口径"></el-table-column>
          </el-table>
        </div>
        <div
          v-if="isNormalShow"
          class="bottom-button"
          style="display: flex; justify-content: flex-end"
        >
          <el-button
            size="mini"
            icon="el-icon-s-data"
            @click="openStatisicDialog"
            >统计</el-button
          >
          <el-button
            size="mini"
            icon="el-icon-folder-opened"
            @click="exportForm"
            >导出
          </el-button>
        </div>
      </div>
      <div
        v-if="isAdvancedShow"
        style="
          width: 463px;
          height: 30px;
          background-color: #4070a2;
          font-size: 16px;
          color: white;
          line-height: 30px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div>区域统计模板</div>
      </div>
      <div
        v-if="isAdvancedShow"
        style="width: 460px; height: 260px; margin-top: 10px"
      >
        <el-table
          :data="templateTableData"
          border
          height="250"
          style="width: 100%"
        >
          <el-table-column prop="areaName" label="名称"></el-table-column>
          <el-table-column prop="areaRemark" label="备注"></el-table-column>
          <!-- <el-table-column prop="areaValue" label="区域坐标"></el-table-column> -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="handleDelete(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        v-if="isAdvancedShow"
        class="bottom-button"
        style="margin-left: 215px"
      >
        <el-button
          size="mini"
          icon="el-icon-circle-plus-outline"
          @click="addArea"
        >
          新增
        </el-button>
      </div>
    </div>
    <div class="sureSearch"></div>
    <AddArea
      :dialogVisible="isAddAreaShow"
      :areaData="areaText"
      @update:dialogVisible="isAddAreaShow = $event"
      @updateTemplateData="updateTemplateData"
    ></AddArea>
    <div class="popup" ref="popup" style="pointer-events: none">
      <InfoPop
        ref="popInfo"
        v-show="isInfoPopShow"
        :dialogVisible="isInfoPopShow"
        @update:dialogVisible="isInfoPopShow = $event"
      ></InfoPop>
    </div>
    <el-dialog
      title="空间查询统计图表"
      :modal="false"
      :close-on-click-modal="true"
      :visible.sync="dialogStatisicVisible"
    >
      <EChartsVue :chart-data="chartData"></EChartsVue>
    </el-dialog>
  </div>
</template>
<script>
import Polygon from "ol/geom/Polygon";
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import dmgis from "@/api/dmgis";
import InfoPop from "../../MapTool/InfoPop.vue";
import {
  getEquipStatistics,
  getQueryTemplate,
  deleteSpatialTemplate,
  getChineseByEnglish,
  searchConditonQueryTemplate,
  spatialQuery,
} from "@/api/EquipmentManagement.js";
import ImageLayer from "ol/layer/Image";
import Overlay from "ol/Overlay";
import AddArea from "./SpatialAddArea.vue";
import EChartsVue from "../../UtilView/ECharts.vue";
import { manyKeywordsQuery } from "@/api/systemTool";
export default {
  name: "equipSpatial",
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
  },
  components: {
    AddArea,
    EChartsVue,
    InfoPop,
  },
  data() {
    return {
      selectedMainType: null, // 第一个下拉框选中的值
      selectedDetailType: null, // 第二个下拉框选中的值
      spatialQueryData: { lineResult: {}, equipResult: {} },
      keywordsList: [],
      isPipeLineShow: false,
      selectedStatType: "", // 绑定的下拉选择值
      isInfoPopShow: false,
      statTypes: [
        // 下拉选择的选项数据
        { label: "类型一", value: "type1" },
        { label: "类型二", value: "type2" },
        { label: "类型三", value: "type3" },
      ],
      queryDataList: [],
      isTotalShow: false,
      pageinfoItem: {
        totalItems: 0,
        currentPage: 1,
        pageSize: 10,
      },
      dmserurl: process.env.VUE_APP_BASE_API + "/dmgis",
      popup: null,
      isLoading: false,
      layerFeatureGroup: [],
      isAddAreaShow: false,
      isNormalShow: true,
      isAdvancedShow: false,
      targetOption: "",
      map: null,
      keywords: [],
      dmProjGroup: [],
      resultDataTemp: [],
      isAllAreaShow: true,
      isNowAreaShow: false,
      isEnvShow: false,
      isCoorShow: false,
      dialogStatisicVisible: false,
      tableData: [],
      tableDataExport: [],
      templateTableData: [],
      areaData: null,
      areaText: "",
      allSpatialQueryData: {},
      projectLayer: null,
      chartData: {
        xAxisData: [],
        seriesData: [],
      },
      querySpatialLayer: null,
      querySpatialAreaLayer: null,
    };
  },
  computed: {
    isSpatialDialogShow() {
      // 返回 prop 的值
      return this.dialogVisible;
    },
    getArea() {
      return this.$store.state.area;
    },
  },
  beforeDestroy() {
    if (this.map) {
      this.map.interaction.cancelYjDraw();
      this.map.map.removeLayer(this.querySpatialAreaLayer);
      this.map.map.removeLayer(this.querySpatialLayer);
      this.map.map.un("dblclick", this.getFeatureByArea);
      this.map.map.un("dblclick", this.getFeatureByMultiArea);
    }
    this.clear();
  },
  watch: {
    queryDataList(newVal) {
      console.log(newVal, "zhegeshiNew");

      this.isInfoPopShow = false;
      if (!newVal) {
        this.$message.warning("请点击要素查询");
        return;
      }
      let rec = newVal[0].rec;
      if (newVal[0].strCor) {
      const xCoordObj = {
  fldname: "x_coord",
  fldtype: "", // 根据需要设置字段类型
  fldval: this.rowClickCoor.x_coord.toString() // 将数字转换为字符串
};

// 创建 y_coord 的对象
const yCoordObj = {
  fldname: "y_coord",
  fldtype: "", // 根据需要设置字段类型
  fldval: this.rowClickCoor.y_coord.toString() // 将数字转换为字符串
};

// 将 xCoordObj 和 yCoordObj 添加到 rec 数组中
newVal[0].rec.push(xCoordObj);
newVal[0].rec.push(yCoordObj);
}
      this.$store.commit("setDetailDataPopList", newVal[0]);
      console.log("空间查询保存的弹窗值",newVal[0])
//       if (newVal[0].strCor) {
//   // 解析 strCor 字符串
//   const strCor = newVal[0].strCor;
//   const coordinates = strCor.split(";").map(point => point.split(" ").map(Number));

//   // 计算 x 和 y 的中点
//   let sumX = 0;
//   let sumY = 0;
//   coordinates.forEach(([x, y]) => {
//     sumX += x;
//     sumY += y;
//   });

//   const midX = sumX / coordinates.length;
//   const midY = sumY / coordinates.length;

//   // 将中点坐标赋值给 this.rowClickCoor
//   this.rowClickCoor = {
//     x_coord: midX,
//     y_coord: midY
//   };

//   console.log(this.rowClickCoor, "this.rowClickCoor");
// }

// if (this.popup) {
//   // 弹窗赋值
//   let coordinatePoint = [
//     this.rowClickCoor.x_coord,
//     this.rowClickCoor.y_coord,
//   ];
//   this.popup.setPosition(coordinatePoint);
//   this.map.panTo(coordinatePoint, 20);
// }
    },
    getArea(newVal) {
      // console.log("绘制完成1");
      this.areaData = newVal;
      this.areaText = JSON.stringify(this.areaData.getCoordinates()[0]);
     
      if (this.isEnvShow) {
        this.getFeatureByArea(this.areaData);
      } else if (this.isCoorShow) {
        this.getFeatureByMultiArea(this.areaData);
      }
    },
    // tableData(newVal) {
    //   this.chartData.xAxisData = [];
    //   this.chartData.seriesData = [];
    //   newVal.forEach((item) => {
    //     this.chartData.xAxisData.push(item.cnname.replace(/\s+/g, ""));
    //     this.chartData.seriesData.push(item.equipmentNum || item.totalLength);
    //   });
    // },
  },
  methods: {
    getMapRefresh(evt, dmProjectLayer) {
      let serviceLayer = dmProjectLayer.serviceLayer;
      let frameState = evt.frameState;
      let imgSvrParam = dmProjectLayer.ImgMapService;
      imgSvrParam.DispRect.minx = frameState.extent[0];
      imgSvrParam.DispRect.miny = frameState.extent[1];
      imgSvrParam.DispRect.maxx = frameState.extent[2];
      imgSvrParam.DispRect.maxy = frameState.extent[3];
      imgSvrParam.imgWid = frameState.size[0];
      imgSvrParam.imgHig = frameState.size[1];
      dmProjectLayer.RefreshMap(
        serviceLayer,
        imgSvrParam,
        frameState.viewState.zoom
      );
    },
    clear() {
      this.map.map
        .getLayers()
        .getArray()
        .forEach((layer) => {
          if (layer.get("layerName") == '空间查询结果图'||layer.get("name")== '空间查询结果图') {
            console.log("找到空间查询结果图层")
            this.map.map.removeLayer(layer);
          }
        });
      },
    //添加工程地图
    addDmProject() {
      let val = {
        color: "RGB(255, 0, 0)",
        conditions: " dmgis_id > 0",
        isDelAccess: true,
        layername:'空间查询结果图',
        range: this.areaText,
        size: "20",
      };
      console.log("空间查询取图的参数", val);
      let dmProjectLayer = new dmgis.olmap.ServiceLayer(
        "TapWaterMap",
        this.dmserurl,
        {
          maxZoom: 18,
          minZoom: 0,
          opacity: 1,
          tileSize: [256, 256],
        }
      );
      //创建点线面时回调
      dmgis.olmap.ServiceLayer.prototype.HandleBuildInfo = function (feature) {
        this.currentindex = feature.index;
      };
      setTimeout(() => {
        dmProjectLayer.serviceLayer = new ImageLayer({
          zIndex: 4,
          name: val.layername,
        });
        this.map.map.addLayer(dmProjectLayer.serviceLayer);
        let querydmParams = new dmgis.object.SpatialConditionQuery();
        let serviceLayer = dmProjectLayer.serviceLayer;
        dmProjectLayer.serviceLayer.setVisible(true);
        querydmParams.polygonStr = "";
        if (val.range !== "") {
          JSON.parse(val.range).forEach((item, index) => {
            let itemGroup = item.join(" ");
            if (index == JSON.parse(val.range).length - 1) {
              querydmParams.polygonStr += itemGroup;
            } else {
              querydmParams.polygonStr += itemGroup + ";";
            }
          });
        }
        let nowExtent = this.map.map.getView().calculateExtent();
        querydmParams.DispRect.minx = nowExtent[0];
        querydmParams.DispRect.miny = nowExtent[1];
        querydmParams.DispRect.maxx = nowExtent[2];
        querydmParams.DispRect.maxy = nowExtent[3];
        var conditions = val.conditions.replace(/</g, "&lt;");

        // 将转义后的字符串赋值给 querydmParams.conditionsList
        querydmParams.conditionsList = conditions;
        console.log(
          querydmParams.conditionsList,
          "条件查询获取的条件参数@@@@@@@@@@@@@@@@@@@@@@@@@@"
        );
        querydmParams.color = val.color;
        if (this.selectedMainType === "管网线段") {
          querydmParams.layers =
            this.$store.state.layersAttribute.filter((layer) =>
              layer.includes("pipeline")
            );
          console.log(querydmParams.layers, "空间查询layers管线");
        } else {
          querydmParams.layers =
            this.$store.state.layersAttribute.filter(
              (layer) => !layer.includes("pipeline")
            );
          console.log(querydmParams.layers, "空间查询layers管点");
        }
        querydmParams.size = val.size.toUpperCase().replace(/\s+/g, "");
        console.log(serviceLayer, querydmParams, "传入refreshMap的两个参数");
        dmProjectLayer.RefreshMap(serviceLayer, querydmParams, 10);
        let watcher = (e) => {
          this.getMapRefresh(e, dmProjectLayer);
        };
        this.dmProjGroup.push({
          layername: val.layername,
          layer: dmProjectLayer,
          watcher: watcher,
        });
        this.map.map.on("moveend", watcher);
      }, 100);
    },
    async handlePointListClick(row) {
      console.log(row, "点击了一行数据row");
      let targetGroup = {};
      let layersAttribute = this.$store.state.layersAttribute;
      let featureAddGroup = [];
      let parts = [row.keywords];
      await manyKeywordsQuery(parts).then((res) => {
        //分类
        for (let key in res.data) {
          let attribute = res.data[key];
          if (!targetGroup[attribute]) {
            targetGroup[attribute] = [];
          }
          targetGroup[attribute].push(key);
        }
      });
      if (layersAttribute.length == 0) {
        this.$message.warning("请先获取服务图层");
        return;
      }
      let getFeatureParams = new dmgis.object.FeatureServiceParam(
        "TapWaterMap"
      );
      for (let item of layersAttribute) {
        if (targetGroup[item.toLowerCase()]) {
          let SpatialQuery = new dmgis.object.SpatialQuery();
          let itemGroup = targetGroup[item.toLowerCase()];
          SpatialQuery.strSql = "";

          itemGroup.forEach((data, index) => {
            if (index !== itemGroup.length - 1) {
              SpatialQuery.strSql += `(keywords='${data}') OR `;
            } else {
              SpatialQuery.strSql += `(keywords='${data}')`;
            }
          });
          getFeatureParams.sql = SpatialQuery;
          getFeatureParams.strlayername = item;
          console.log(getFeatureParams, "调取服务传递的参数");
          try {
            await this.projectLayer
              .SendFeatureMapService(getFeatureParams)
              .then((res) => {
                console.log(res, "点击一行服务返回的数据");
                if (res.objset) {
                  this.queryDataList = res.objset;
                  this.queryDataList[0].dataName = item;
                  let that=this;
                  res.objset.forEach((feature) => {
                    let objectData = {};
                    if (this.isPipeLineShow) {
                      // 首先使用 split 方法将字符串按分号分割成两个坐标点的数组
                      let points = feature.strCor.split(";");

                      // 然后分别处理每个坐标点，再计算中间值
                      let x_coords = [];
                      let y_coords = [];

                      points.forEach((point) => {
                        // 再次使用 split 方法将每个坐标点按空格分割成 x 和 y 值
                        let [x, y] = point.split(" ");
                        // 将 x 和 y 值分别添加到对应的数组中
                        x_coords.push(parseFloat(x));
                        y_coords.push(parseFloat(y));
                      });

                      // 计算 x 和 y 的中间值
                      let x_coord = (x_coords[0] + x_coords[1]) / 2;
                      let y_coord = (y_coords[0] + y_coords[1]) / 2;

                      // 将中间值封装成对象
                      this.rowClickCoor = {
                        x_coord,
                        y_coord,
                      };
                      objectData.x_coord = x_coord;
                      objectData.y_coord = y_coord;
                      // 创建 x_coord 的对象

                      console.log("空间查询处理好的管线xy坐标值",x_coord,y_coord)
                    } else {
                      let points = feature.strPnt.split(";");

                      // 然后分别处理每个坐标点，再计算中间值
                      let x_coords = [];
                      let y_coords = [];

                      points.forEach((point) => {
                        // 再次使用 split 方法将每个坐标点按空格分割成 x 和 y 值
                        let [x, y] = point.split(" ");
                        // 将 x 和 y 值分别添加到对应的数组中
                        x_coords.push(parseFloat(x));
                        y_coords.push(parseFloat(y));
                      });

                      this.rowClickCoor = {
                        x_coord: x_coords[0],
                        y_coord: y_coords[0],
                      };
                    }
                    feature.rec.forEach((rec) => {
                      objectData[rec.fldname] = rec.fldval;
                    });
                    objectData.x_coord=this.rowClickCoor.x_coord;
                    objectData.y_coord=this.rowClickCoor.y_coord;
                    featureAddGroup.push(objectData);
                  });
                }
              });
          } catch (error) {
            console.error("获取图层特征时出错:", error);
          }
        }
      }

      // if (featureAddGroup.length == 1) {
      //   this.map.panTo(
      //     [featureAddGroup[0].x_coord, featureAddGroup[0].y_coord],
      //     13
      //   );
      // }
    },
    handleMainSelectChange() {
      if(this.isEnvShow||this.isCoorShow){this.clear();this.addDmProject();}
      // 清空第二个下拉框的选中值
      this.selectedDetailType = null;
      // 根据第一个下拉框的选中值更新表格数据
      this.updateTableData();
      if (this.selectedMainType === "管网线段") {
        // 清空图表数据
        this.chartData.xAxisData = [];
        this.chartData.seriesData = [];

        // 遍历管网线段数据
        this.spatialQueryData.管网线段.forEach((segment) => {
          // 将 lineDiameter 作为 x 轴数据，lineLen 作为 y 轴数据
          this.chartData.xAxisData.push(segment.lineDiameter);
          this.chartData.seriesData.push(segment.lineLen.toFixed(3));
        });
        console.log(this.chartData, "统计数据");
        // 显示管网线段相关数据
        this.isPipeLineShow = true;
        this.total = this.spatialQueryData.lineTotalLen.toFixed(3);
      } else if (this.selectedMainType === "管网节点") {
        // 清空图表数据
        this.chartData.xAxisData = [];
        this.chartData.seriesData = [];

        // 遍历管网节点数据
        this.spatialQueryData.管网节点.forEach((node) => {
          // 将 equipName 作为 x 轴数据，equipNum 作为 y 轴数据
          this.chartData.xAxisData.push(node.equipName);
          this.chartData.seriesData.push(node.equipNum);
        });
        console.log(this.chartData, "统计数据");
        // 不显示管网线段相关数据
        this.isPipeLineShow = false;
        this.total = this.spatialQueryData.equipTotalNum;
      }
      this.isTotalShow = true;
    },
    handleDetailSelectChange() {
      // 根据第二个下拉框的选中值更新表格数据
      this.updateTableData();
    },
    updateTableData() {
      console.log("选择输出", this.selectedMainType, this.selectedDetailType);
      if (
        !this.selectedMainType ||
        !this.spatialQueryData[this.selectedMainType]
      ) {
        this.tableData = [];
        this.tableDataExport = [];
        return;
      }

      if (!this.selectedDetailType) {
        this.tableData = [];
        this.tableDataExport = [];
        return;
      }

      // 获取选中的详细类型对应的数据
      const selectedData = this.spatialQueryData[this.selectedMainType].find(
        (item) =>
          (this.selectedMainType === "管网线段"
            ? item.lineDiameter
            : item.equipName) === this.selectedDetailType
      );

      console.log("选中的数据", selectedData);

      if (this.selectedMainType === "管网线段") {
        this.total = selectedData.lineLen.toFixed(3);
        console.log("选中的管网线段", selectedData.lineData);
        this.tableData = selectedData.lineData.map((item) => ({
          cnname: item.keywords,
          equipmentNum: item.diameter,
          material: item.material,
          ...item,
        }));
        this.tableDataExport = selectedData.lineData.map((item) => ({
          ...item,
        }));
      } else if (this.selectedMainType === "管网节点") {
        this.total = selectedData.equipNum;
        console.log("选中的管网节点", selectedData.equipData);
        this.tableData = selectedData.equipData.map((item) => ({
          cnname: item.keywords,
          equipmentNum: item.diameter,
          material: item.material,
          ...item,
        }));
        this.tableDataExport = selectedData.equipData.map((item) => ({
          ...item,
        }));
      }
    },
    getDetailOptions(mainType) {
      if (mainType === "管网线段") {
        return this.spatialQueryData[mainType].map((item) => item.lineDiameter);
      } else if (mainType === "管网节点") {
        return this.spatialQueryData[mainType].map((item) => item.equipName);
      }
      return [];
    },

    handleSelectChange(event) {
      console.log("选中的统计类型:", event.target.value);
      // 在这里可以处理选择事件的逻辑
    },
    handleCurrentChange(page) {
      this.pageinfoItem.currentPage = page;
    },
    initMap() {
      setTimeout(() => {
        this.map = this.$store.getters.Map;
        if (this.map) {
          if (this.popup == null) {
            let elPopup = this.$refs.popup;
            this.popup = new Overlay({
              element: elPopup,
              position: null,
              offset: [0, -10],
              positioning: "bottom-center",
            });
            this.map.map.addOverlay(this.popup);
          }
        } else {
          console.error("地图实例未找到");
        }
        this.projectLayer = this.$store.getters.projectLayer;
        this.querySpatialLayer =
          this.map.layer.createVectorLayer("空间查询点图层");
        this.querySpatialAreaLayer =
          this.map.layer.createVectorLayer("空间查询面图层");
      }, 1000); // 延迟 1000 毫秒（1秒）后执行
    },
    getSpatialQuery() {
      this.spatialQueryData = this.allSpatialQueryData;
      if (this.spatialQueryData["管网线段"]) {
        this.isLoading = false;
        this.selectedMainType = "管网线段";
        this.isTotalShow = true;
        this.isPipeLineShow = true;
        this.total = this.spatialQueryData.lineTotalLen.toFixed(3);
      }
    },
    changeMenu(val) {
      console.log(val, "切换顶部按钮");
      if (val == "normal") {
        this.isNormalShow = true;
        this.isAdvancedShow = false;
      } else {
        this.isNormalShow = false;
        this.isAdvancedShow = true;
      }
    },
    changeArea(val) {
      this.map.interaction.cancelYjDraw();
      this.querySpatialLayer.getSource().clear();
      this.querySpatialAreaLayer.getSource().clear();
      // this.map.map.un("dblclick", this.getFeatureByArea1);
      // this.map.map.un("dblclick", this.getFeatureByMultiArea1);
      switch (val) {
        case "all":
          this.isAllAreaShow = true;
          this.isNowAreaShow = false;
          this.isEnvShow = false;
          this.isCoorShow = false;
          this.isLoading = true;
          this.getSpatialQuery();
          break;
        case "now":
          this.isAllAreaShow = false;
          this.isNowAreaShow = true;
          this.isEnvShow = false;
          this.isCoorShow = false;
          break;

        case "env":
          this.map.interaction.addNewAreaDraw("Rectangle", 1);
          this.addEnvArea();
          this.isAllAreaShow = false;
          this.isNowAreaShow = false;
          this.isEnvShow = true;
          this.isCoorShow = false;
          break;
        case "coor":
          this.map.interaction.addNewAreaDraw("Polygon", 1);
          this.addCoorArea();
          this.isAllAreaShow = false;
          this.isNowAreaShow = false;
          this.isEnvShow = false;
          this.isCoorShow = true;
          break;
      }
    },
    closeDialog() {
      // 通过修改 prop 来关闭弹窗
      this.$emit("update:dialogVisible", false);
    },
    targetSelect() {
      this.querySpatialLayer.getSource().clear();
      this.querySpatialAreaLayer.getSource().clear();
      let areaDataSelect = JSON.parse(this.targetOption);
      this.areaText = this.targetOption;
      let polygon = new Polygon([areaDataSelect]);
      this.map.map.getView().fit(polygon, {
        duration: 1000,
      });
      this.map.layer.addPolygonsToLayer(
        this.querySpatialAreaLayer,
        [areaDataSelect],
        {
          fill: "rgba(255, 255, 255, 0.2)",
          strokeColor: "#6db6d2",
          strokeWidth: 2,
        }
      );
      this.isLoading = true;
      //调用dmgis服务
      let resultData = [];
      let getFeatureParams = new dmgis.object.FeatureServiceParam(
        "TapWaterMap"
      );
      let SpatialQuery = new dmgis.object.SpatialQuery();
      let areaPos = "";
      areaDataSelect.forEach((item, index) => {
        let itemGroup = item.join(" ");
        if (index == areaDataSelect.length - 1) {
          areaPos += itemGroup;
        } else {
          areaPos += itemGroup + ";";
        }
      });
      SpatialQuery.strPos = areaPos;
      getFeatureParams.sql = SpatialQuery;
      let layersAttribute = this.$store.state.layersAttribute;
      if (layersAttribute.length == 0) {
        this.$message.warning("请先获取服务图层");
        this.isLoading = false;
        return;
      }
      let requestNum = 0;
      requestNum = this.$store.state.layersAttribute.length;
      async function getFeatureByAreaSon() {
        for (let item of layersAttribute) {
          getFeatureParams.strlayername = item;
          try {
            await this.projectLayer
              .SendFeatureMapService(getFeatureParams)
              .then((res) => {
                if (res.objset) {
                  let dataObjectgroup = [];
                  res.objset.map((item) => {
                    let dataObject = {};
                    item.rec.forEach((data) => {
                      dataObject[data.fldname] = data.fldval;
                    });
                    dataObjectgroup.push(dataObject);
                  });
                  resultData.push({
                    layername: getFeatureParams.strlayername,
                    data: dataObjectgroup,
                  });
                }
                // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                //   function (feature) {
                //     if (feature.objset) {
                //       let dataObjectgroup = [];
                //       feature.objset.map((item) => {
                //         let dataObject = {};
                //         item.rec.forEach((data) => {
                //           dataObject[data.fldname] = data.fldval;
                //         });
                //         dataObjectgroup.push(dataObject);
                //       });
                //       resultData.push({
                //         layername: getFeatureParams.strlayername,
                //         data: dataObjectgroup,
                //       });
                //     }
                //   };
              });
          } catch (error) {
            console.error("获取图层数据请求出错:", error);
          } finally {
            requestNum--;
            if (requestNum == 0) {
              this.$message.success("数据获取成功");
              this.isLoading = false;
              let engGroup = [];
              let chnGroup = [];
              //英取汉
              resultData.forEach((item) => {
                // let parts = item.layername.split("_");
                // let result = parts.slice(0, 2).join("_");
                // item.layername = result;
                engGroup.push(item.layername);
              });
              //汉取英
              await getChineseByEnglish(engGroup).then((res) => {
                chnGroup = res.data;
              });
              this.keywordsList = [];
              console.log(resultData, "resultData");

              this.areaTableData = resultData.map((item) => {
                item.data.forEach((data) => {
                  this.keywordsList.push(data.keywords);
                });
                let dataName = chnGroup[item.layername];
                return {
                  cnname: dataName,
                  equipmentNum: item.data.length,
                };
              });
              this.addDmProject();
              spatialQuery({ keywordsList: this.keywordsList }).then((res) => {
                if (res.code == 200) {
                  console.log("空间查询获取数据1", res.data);
                  this.spatialQueryData = res.data;
                  if (this.spatialQueryData["管网线段"]) {
                    this.selectedMainType = "管网线段";
                    this.total = this.spatialQueryData.lineTotalLen.toFixed(3);
                    this.isPipeLineShow = true;
                  } else {
                    this.isPipeLineShow = false;
                    this.total = this.spatialQueryData.equipTotalNum;
                  }
                }
              });
            }
          }
        }
      }
      getFeatureByAreaSon.call(this);
    },
    handleDelete(index, row) {
      // 这里编写删除行的逻辑
      // 例如，从 tableData 中移除该行
      deleteSpatialTemplate({ id: row.id }).then((res) => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
          for (let i = 0; i < this.templateTableData.length; i++) {
            if (this.templateTableData[i].id == row.id) {
              this.templateTableData.splice(i, 1);
            }
          }
        }
      });
    },
    // 新增区域按钮点击事件
    addArea() {
      this.map.interaction.addNewAreaDraw("Polygon", 1);
      this.map.map.on("dblclick", (event) => {
        // 你的处理逻辑
        this.isAddAreaShow = true;
        // 可以在这里执行你想要进行的操作，比如完成绘制等
      });
    },
    //自定义矩形区域点击按钮
    addEnvArea() {
      this.areaData = null;
      this.areaText = "";
      // this.map.map.on("dblclick", this.getFeatureByArea);
    },

    getFeatureByArea() {
      this.isLoading = true;
      this.map.map.un("dblclick", this.getFeatureByArea);
      if (this.areaData) {
        // this.isLoading = true;
        //调用dmgis服务
        let resultData = [];

        let areaRect = this.areaData.getCoordinates()[0];
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        let rect = new dmgis.object.Envelope(); //矩形范围
        rect.minx = areaRect[0][0];
        rect.miny = areaRect[0][1];
        rect.maxx = areaRect[2][0];
        rect.maxy = areaRect[2][1];
        SpatialQuery.env = rect; //矩形
        getFeatureParams.sql = SpatialQuery;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          this.isLoading = false;
          return;
        }

        let requestNum = 0;
        requestNum = this.$store.state.layersAttribute.length;
        async function getFeatureByAreaSon() {
          for (let item of layersAttribute) {
            getFeatureParams.strlayername = item;
            try {
              await this.projectLayer
                .SendFeatureMapService(getFeatureParams)
                .then((res) => {
                  if (res.objset) {
                    let dataObjectgroup = [];
                    res.objset.map((item) => {
                      let dataObject = {};
                      item.rec.forEach((data) => {
                        dataObject[data.fldname] = data.fldval;
                      });
                      dataObjectgroup.push(dataObject);
                    });
                    resultData.push({
                      layername: getFeatureParams.strlayername,
                      data: dataObjectgroup,
                    });
                  }
                  // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                  //   function (feature) {
                  //     if (feature.objset) {
                  //       let dataObjectgroup = [];
                  //       feature.objset.map((item) => {
                  //         let dataObject = {};
                  //         item.rec.forEach((data) => {
                  //           dataObject[data.fldname] = data.fldval;
                  //         });
                  //         dataObjectgroup.push(dataObject);
                  //       });
                  //       resultData.push({
                  //         layername: getFeatureParams.strlayername,
                  //         data: dataObjectgroup,
                  //       });
                  //     }
                  //   };
                });
            } catch (error) {
              console.error("获取图层特征时出错:", error);
            } finally {
              requestNum--;
              if (requestNum == 0) {
                this.$message.success("数据获取成功");
                this.isLoading = false;
                let engGroup = [];
                let chnGroup = [];
                //英取汉
                resultData.forEach((item) => {
                  // let parts = item.layername.split("_");
                  // let result = parts.slice(0, 2).join("_");
                  // item.layername = result;
                  engGroup.push(item.layername);
                });
                //汉取英
                await getChineseByEnglish(engGroup).then((res) => {
                  chnGroup = res.data;
                });
                this.keywordsList = [];
                console.log(resultData, "resultData");

                this.areaTableData = resultData.map((item) => {
                  item.data.forEach((data) => {
                    this.keywordsList.push(data.keywords);
                  });
                  let dataName = chnGroup[item.layername];
                  return {
                    cnname: dataName,
                    equipmentNum: item.data.length,
                  };
                });
                spatialQuery({ keywordsList: this.keywordsList }).then(
                  (res) => {
                    if (res.code == 200) {
                      console.log("空间查询获取数据1", res.data);
                      this.isLoading = false;
                      this.spatialQueryData = res.data;
                      if (this.spatialQueryData["管网线段"]) {
                        this.selectedMainType = "管网线段";
                        this.total =
                          this.spatialQueryData.lineTotalLen.toFixed(3);
                      } else {
                        this.total = this.spatialQueryData.equipTotalNum;
                      }
                    }
                  }
                );
                this.addDmProject();
              }
            }
          }
        }
        getFeatureByAreaSon.call(this);
      }
    },
    // 新增自定义多边形按钮点击事件
    addCoorArea() {
      this.areaData = null;
      this.areaText = "";
      // this.map.map.on("dblclick", this.getFeatureByMultiArea);
    },
    getFeatureByMultiArea() {
      this.map.map.un("dblclick", this.getFeatureByArea);
      this.isLoading = true;
      if (this.areaData) {
        // this.isLoading = true;
        //调用dmgis服务
        let resultData = [];
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        let areaPos = "";
        this.areaData.getCoordinates()[0].forEach((item, index) => {
          let itemGroup = item.join(" ");
          if (index == this.areaData.getCoordinates()[0].length - 1) {
            areaPos += itemGroup;
          } else {
            areaPos += itemGroup + ";";
          }
        });
        SpatialQuery.strPos = areaPos;
        getFeatureParams.sql = SpatialQuery;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          this.isLoading = false;
          return;
        }
        let requestNum = 0;
        requestNum = this.$store.state.layersAttribute.length;

        async function getFeatureByAreaSon() {
          for (let item of layersAttribute) {
            getFeatureParams.strlayername = item;
            try {
              await this.projectLayer
                .SendFeatureMapService(getFeatureParams)
                .then((res) => {
                  if (res.objset) {
                    let dataObjectgroup = [];
                    res.objset.map((item) => {
                      let dataObject = {};
                      item.rec.forEach((data) => {
                        dataObject[data.fldname] = data.fldval;
                      });
                      dataObjectgroup.push(dataObject);
                    });
                    resultData.push({
                      layername: getFeatureParams.strlayername,
                      data: dataObjectgroup,
                    });
                  }
                  // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                  //   function (feature) {
                  //     if (feature.objset) {
                  //       let dataObjectgroup = [];
                  //       feature.objset.map((item) => {
                  //         let dataObject = {};
                  //         item.rec.forEach((data) => {
                  //           dataObject[data.fldname] = data.fldval;
                  //         });
                  //         dataObjectgroup.push(dataObject);
                  //       });
                  //       resultData.push({
                  //         layername: getFeatureParams.strlayername,
                  //         data: dataObjectgroup,
                  //       });
                  //     }
                  //   };
                });
            } catch (error) {
              console.error("获取图层特征时出错:", error);
            } finally {
              requestNum--;
              if (requestNum == 0) {
                this.$message.success("数据获取成功");
                this.isLoading = false;
                let engGroup = [];
                let chnGroup = [];
                //英取汉
                resultData.forEach((item) => {
                  // let parts = item.layername.split("_");
                  // let result = parts.slice(0, 2).join("_");
                  // item.layername = result;
                  engGroup.push(item.layername);
                });
                //汉取英
                await getChineseByEnglish(engGroup).then((res) => {
                  chnGroup = res.data;
                });
                this.keywordsList = [];
                this.areaTableData = resultData.map((item) => {
                  item.data.forEach((data) => {
                    this.keywordsList.push(data.keywords);
                  });
                  let dataName = chnGroup[item.layername];
                  return {
                    cnname: dataName,
                    equipmentNum: item.data.length,
                  };
                });
                spatialQuery({ keywordsList: this.keywordsList }).then(
                  (res) => {
                    if (res.code == 200) {
                      console.log("空间查询获取数据1", res.data);
                      this.isLoading = false;
                      this.spatialQueryData = res.data;
                      if (this.spatialQueryData["管网线段"]) {
                        this.selectedMainType = "管网线段";
                        this.total =
                          this.spatialQueryData.lineTotalLen.toFixed(3);
                      } else {
                        this.total = this.spatialQueryData.equipTotalNum;
                      }
                    }
                  }
                );
                this.addDmProject();
              }
            }
          }
        }
        getFeatureByAreaSon.call(this);
      }
      // this.map.interaction.cancelYjDraw();
      this.addCoorArea();
      // const h = this.$createElement;
      // this.$msgbox({
      //   title: "多边形空间查询",
      //   message: h("p", null, [h("span", null, "是否查询该区域? ")]),
      //   showCancelButton: true,
      //   distinguishCancelAndClose: true,
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      // })
      //   .then((action) => {
      //     if (action == "confirm") {

      //     }
      //   })
      //   .catch(() => {

      //   });
    },
    openStatisicDialog() {
      this.dialogStatisicVisible = true;
    },
    async exportForm() {
      if (this.tableDataExport.length === 0) {
        this.$message.warning("暂无可导出的数据!");
        return;
      }

      let wb = XLSX.utils.book_new();
      console.log(this.tableDataExport, "this.resultDataTemp");

      // 获取所有键名（表头）
      let keyGroup = Object.keys(this.tableDataExport[0]);
      let arrayTemp = [];

      // 将键名（表头）转换为中文
      let res = await getChineseByEnglish(keyGroup);
      if (!res || !res.data) {
        console.error("getChineseByEnglish returned invalid data:", res);
        return;
      }

      let headerRow = [];
      for (let key in res.data) {
        headerRow.push(res.data[key]);
      }
      arrayTemp.push(headerRow);

      // 遍历表格数据
      for (const item of this.tableDataExport) {
        let row = [];
        for (let key in item) {
          row.push(item[key]);
        }
        arrayTemp.push(row);
      }

      // 创建工作表
      let ws = XLSX.utils.aoa_to_sheet(arrayTemp);
      XLSX.utils.book_append_sheet(wb, ws, "空间查询统计表");

      // 保存文件
      XLSX.writeFile(wb, "空间查询统计表.xlsx");
    },
    updateTemplateData() {
      this.templateTableData = [];
      getQueryTemplate().then((res) => {
        this.templateTableData = res.data;
      });
    },
  },

  mounted() {
    this.initMap();
    this.isLoading = true;
    getQueryTemplate().then((res) => {
      this.templateTableData = res.data;
    });
    spatialQuery({ keywordsList: this.keywordsList }).then((res) => {
      if (res.code == 200) {
        console.log("空间查询获取数据1", res.data);
        this.isLoading = false;
        this.spatialQueryData = res.data;
        this.allSpatialQueryData = this.spatialQueryData;
        if (this.spatialQueryData["管网线段"]) {
          this.selectedMainType = "管网线段";
          this.isTotalShow = true;
          this.isPipeLineShow = true;
          this.total = this.spatialQueryData.lineTotalLen.toFixed(3);
        }
        if (this.selectedMainType === "管网线段") {
          // 清空图表数据
          this.chartData.xAxisData = [];
          this.chartData.seriesData = [];

          // 遍历管网线段数据
          this.spatialQueryData.管网线段.forEach((segment) => {
            // 将 lineDiameter 作为 x 轴数据，lineLen 作为 y 轴数据
            this.chartData.xAxisData.push(segment.lineDiameter);
            this.chartData.seriesData.push(segment.lineLen.toFixed(3));
          });
          console.log(this.chartData, "统计数据");
          // 显示管网线段相关数据
          this.isPipeLineShow = true;
          this.total = this.spatialQueryData.lineTotalLen.toFixed(3);
        } else if (this.selectedMainType === "管网节点") {
          // 清空图表数据
          this.chartData.xAxisData = [];
          this.chartData.seriesData = [];

          // 遍历管网节点数据
          this.spatialQueryData.管网节点.forEach((node) => {
            // 将 equipName 作为 x 轴数据，equipNum 作为 y 轴数据
            this.chartData.xAxisData.push(node.equipName);
            this.chartData.seriesData.push(node.equipNum);
          });
          console.log(this.chartData, "统计数据");
          // 不显示管网线段相关数据
          this.isPipeLineShow = false;
          this.total = this.spatialQueryData.equipTotalNum;
        }
      }
    });

    // let names = [
    //   "clampcollar_info",
    //   "threadedvalve_info",
    //   "unconfirmed_pipelines_center",
    // ];

    // getChineseByEnglish(names).then((res) => {});
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox {
  color: white;
}
.spatialDialogContainer {
  width: 25vw;
  color: white;
  position: absolute;
  top: 5vh;
  right: -19vw;
  height: 46vh;
  z-index: 2;
  .spatialDialogTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 1rem;
    background-color: #285383;
    .title-left,
    .title-right {
      display: flex;
      align-items: center;
    }
    .bar {
      width: 5px; /* 小竖条的宽度 */
      height: 20px; /* 小竖条的高度 */
      background-color: white; /* 小竖条的颜色 */
      margin-right: 10px; /* 小竖条和文字之间的间距 */
    }
    .icon {
      width: 20px; /* 小方框的宽度 */
      height: 20px; /* 小方框的高度 */
      // border: 1px solid #4998f2; /* 小方框的边框 */
      margin-left: 5px; /* 小方框之间的间距 */
    }
    .icon:hover {
      color: #4998f2;
    }
    .icon:focus {
      color: #4998f2;
    }
  }
  .spatialDialogContent {
    padding: 10px;
    display: flex;
    flex-direction: column;
    background-color: #285383;
    font-size: 0.8rem;
    .contentButton {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px; /* 与下半部分内容的间距 */
      .menuButton {
        width: 50%;
        text-align: center;
        cursor: pointer;
      }
      .menuButton.active {
        // color: rgb(8, 46, 82);
        border-bottom: 2px solid white;
      }
    }
    .menuArea {
      cursor: pointer;
      margin: 0 2px !important;
    }
    .menuArea.active {
      background-color: #c4c6c8 !important;
    }
    .contentBox {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      .formRow {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .search_input {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          input {
            width: 80%;
          }
        }
      }
      .label {
        width: 100px;
        margin-right: 10px;
      }

      select,
      textarea,
      button {
        width: 100%;
        color: white !important;
        background-color: #4070a2;
        border: none; /* 去除边框 */
        outline: none; /* 去除焦点时的轮廓线 */
        font-size: 0.8rem;
        height: 1.5rem;
      }

      button {
        margin-right: 10px; /* 按钮之间的间距 */
      }
      button:hover {
        background-color: #4998f2;
      }
      button:focus {
        background-color: #4998f2;
      }
      textarea {
        height: 5rem;
      }

      /* 最后一行的按钮不需要 label，可以单独设置样式 */
      .formRow:last-child {
        justify-content: flex-end;
      }

      .formRow:last-child .button {
        margin-left: 10px; /* 按钮之间的间距，而不是右边距 */
      }
    }
  }
}
.tablePage {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: center;
  ::v-deep .el-pagination {
    button {
      color: #fff;
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
    }
    .el-pagination__jump {
      color: #fff;
      background: transparent;
    }
    .el-input__inner {
      background: transparent;
      color: #fff;
    }
  }
  ::v-deep .el-pagination__total {
    color: #fff;
  }
  ::v-deep .el-pager {
    color: #fff;
    .number {
      margin: 0 0.3vw;
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
    }

    .btn-quickprev {
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
      color: #fff;
    }
    .btn-quicknext {
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
      color: #fff;
    }
  }
}
</style>
